package com.jy.web.qr.controller;

import com.jy.framework.annotation.RequiresAction;
import com.jy.framework.annotation.SysLog;
import com.jy.framework.exception.MyException;
import com.jy.framework.sys.entity.SysMenuEntity;
import com.jy.framework.sys.service.SysConfigService;
import com.jy.framework.sys.service.SysMenuService;
import com.jy.framework.utils.R;
import com.jy.framework.utils.os.OSProperties;
import com.jy.framework.utils.qr.ImgQrTool;
import com.jy.framework.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.jy.framework.base.BaseController;

import com.jy.web.qr.entity.ProductionQrEntity;
import com.jy.web.qr.service.ProductionQrService;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;


/**
 * 产品二维码数据表
 *
 * @author JuiceYan
 * @email JuiceYan@jy.com
 * @date 2018-12-28 22:02:02
 */
@Api(tags = "产品二维码数据表")
@RestController
@RequestMapping("qr/productionqr")
public class ProductionQrController extends BaseController<ProductionQrService, ProductionQrEntity> {
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    OSProperties osProperties;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 生成访问产品二维码
     */
    @ApiOperation("生成访问产品二维码文件")
    @GetMapping(value = "/generate/{id}")
    @ResponseBody
    @RequiresAction("generate")
    public Object generate(@PathVariable("id") Integer productionQrId) {
        ProductionQrEntity productionqr = service.getById(productionQrId);

        String data = sysConfigService.queryByKey("host");
        if (null == data){
            throw new MyException("请在系统参数配置host！");
        }
        ImgQrTool.encode(osProperties.getQrBaseUrl().replace("{host}",data) + productionQrId, 500, 500, osProperties.getQrSrcDir(), osProperties.getQrDir());
//        response.setHeader("Content-Disposition", "attachment;filename=" + new String(productionqr.getName() .getBytes("gbk"),"ISO-8859-1"));
        return renderFile(productionqr.getName()+ ".jpg", osProperties.getQrDir());
    }


    /**
     * 添加二维码链接菜单
     */
    @ApiOperation("添加二维码链接菜单")
    @SysLog("添加二维码链接菜单")
    @PostMapping("/saveQrLinkMenu")
    @RequiresAction("save")
    public R saveQrLinkMenu(@RequestBody SysMenuEntity menu) {
        menu.setPerms("ProductionQrController:save");
//      二维码链接菜单默认上级
        menu.setParentId(282L);
//        默认是菜单
        menu.setType(1);
        //数据校验
        ValidatorUtils.validateEntity(menu);
        sysMenuService.save(menu);
        return R.ok();
    }

}
